<?php
/*******单例模式，mysql*******/
class MysqlDB{
    private $tables;
    private $con;
    private static $_instance = NULL;
    private $ismysqli;
    private $res;
    private $log;
    public  $page_count;
    public function __construct($table_name) {
        
        global $_G;
        $this->ismysqli=function_exists('mysqli_connect');
        $this->tables=$_G["db"]["table_fix"]."_".$table_name;
        $this->log=Logclass::getInstance();
        
        if($this->ismysqli){
            $this->con=  mysqli_connect($_G["db"]["host_name"],$_G["db"]["user_name"],$_G["db"]["pwd"]);
        } else{
            $this->con=  mysql_connect($_G["db"]["host_name"],$_G["db"]["user_name"],$_G["db"]["pwd"]);
        }
        if (!$this->con)
        {
          $t=date("Y-m-d h:i:s",  time());
          Debugshow::show("错误码:".$this->get_errorno().",连接数据库失败");
          $this->log->writeline("错误码:".$this->get_errorno().",连接数据库失败");
         
        }else{
            $charset="utf8";
            if(strpos("-", $_G['charset'])){
                $charset=str_replace("-", "", $_G['charset']);
            }
            $this->query("set names {$charset}"); 
        }
        $resdb=($this->ismysqli?mysqli_select_db($this->con,$_G["db"]["dbname"]):mysql_select_db($_G["db"]["dbname"]));
        if(!$resdb){
            Debugshow::show("错误码:".$this->get_errorno().",连接数据库{$_G["db"]["dbname"]}不存在");
            $this->log->writeline("错误码:".$this->get_errorno().",连接数据库{$_G["db"]["dbname"]}不存在");
        }
    }
    //获得执行sql的错误代码
    public function get_errorno(){
        return $this->ismysqli?mysqli_errno($this->con):  mysql_errno();
    }
    //获得执行sql的错误提示
    public function get_error(){
        return $this->ismysqli?mysqli_error($this->con):  mysql_error();
    }
    //执行sql函数
    public function query($sql){
        if($sql){
            $this->res=($this->ismysqli?mysqli_query($this->con,$sql): mysql_query($sql,$this->con));
            if($this->res){
                //$this->log->writeline("sql语句:{$sql}");
                return $this->res;
            }  else {
                //执行失败或出错
                 Debugshow::show("执行sql错误:".$this->get_error().".sql语句:{$sql}");
                 $this->log->writeline("执行sql错误:".$this->get_error().".sql语句:{$sql}");
                 return FALSE;
            }
        }
    }
    //执行sql函数
    public function execute($sql){
        if($sql){
            $this->res=($this->ismysqli?mysqli_query($this->con,$sql): mysql_query($sql,$this->con));
            $meth=  $this->get_fetch_array_method();
            if($this->res){
                $data=array();
                while ($rows=$meth($this->res)){
                    $data[]=$rows;
                }
                $this->free_result($this->res);
                $this->log->writeline("执行sql:{$sql}");
                return $data;
            }  else {
                //执行失败或出错
                 Debugshow::show("执行sql错误:".$this->get_error().".sql语句:{$sql}");
                 $this->log->writeline("执行sql错误:".$this->get_error().".sql语句:{$sql}");
                 return FALSE;
            }
        }
    }
    public function select_page($datas="*",$where="1=1",$page=1,$page_size=20,$orderby=''){
         $sql="";
         $count=0;
         $data=array();
         if(is_array($datas)){
             $fields=  implode(",", $datas);
             $sql="select {$fields} from {$this->tables} ".($where?"where {$where}":""); 
         }else
         {
             $sql="select {$datas} from {$this->tables} ".($where?"where {$where}":""); 
         }
         
         if($where){
            $count=  $this->get_count($where); 
         }
        
         $page_count=  ceil($count/$page_size);
         $this->page_count=$page_count;
       
         if($page<=$page_count){
             $start=($page-1)*$page_size;
             $sql.=" {$orderby} limit {$start},{$page_size} ";
         
             $res=  $this->query($sql);
             if($res){
                 $data=array();
                   $metho=  $this->get_fetch_array_method();
                    while ($row=$metho($res)){
                        $data[]=$row;
                    }
                    $this->free_result($res);
                    return $data;
             }else{
                 return FALSE;
             }
         }else{
             return FALSE;
         }
         
    }

    //析构时，关闭数据连接。
    public function __destruct() {
        $this->ismysqli?mysqli_close($this->con):mysql_close($this->con);
    }
    //sql select查询方法,参数1：要取出的字段名,字段名可以是数组如：array("*"),array("user_name","password"),也可是字符串*,base_name,password
    //参数2：查询的条件
    public function select($datas="*",$where="1=1"){
         $sql="";
         $data=array();
         if(is_array($datas)){
             $fields=  implode(",", $datas);
             $sql="select {$fields} from {$this->tables} ".($where?"where {$where}":""); 
         }else
         {
             $sql="select {$datas} from {$this->tables} ".($where?"where {$where}":""); 
         }
         $res=  $this->query($sql);
         if($res){
         $metho=  $this->get_fetch_assoc_method();
         while ($row=$metho($res)){
             $data[]=$row;
         }
         $this->free_result($res);
         return $data;
         }else{
             return FALSE;
         }
    }
     //sql select查询方法,只取一条记录,参数1：要取出的字段名,字段名可以是数组如：array("*"),array("user_name","password"),也可是字符串*,base_name,password
    //参数2：查询的条件
    public function get_one($datas="*",$where="1=1"){
        $data=$this->select($datas,$where." limit 1");
        if(isset($data[0]))
        return $data[0];
        else{
            return FALSE;
        }
    }

    //获取按条件查询的结果数量，参数：条件
    //返回值：查询数量
    public function get_count($where="1=1"){
        $sql="";
        if($where){
             $sql="select count(*) from {$this->tables} ".($where?"where {$where}":""); 
        }  else {
             $sql="select count(*) from {$this->tables}";
        }
        $res=  $this->query($sql);
        $meth=  $this->get_fetch_row_method();
        $row=$meth($res);
        $this->free_result($res);
        return $row[0];
    }
    //sql 删除方法,参数：要删除的条件
    //执行成功返回true，否则返回False
    public function delete($where='1=1'){
        $sql="";
        if($where){
            $sql="delete from {$this->tables} ".($where?"where {$where}":""); 
            $res=  $this->query($sql);
            if($res){
                return TRUE;
            }else{
                return FALSE;
            }
        }
       return FALSE;
    }
    //sql insert 更新方法,参数1：可以为数组，也可以为字符串，当是数组的时候格式如下：array("字段名"=>"值","字段名2"=>"值2"....)，当是字符串时候，格式如下：字段名=值,字段名2=值,...
    //参数2：where条件，更新条件
    //执行失败返回FALSE
    public function update($fields,$where='1=1'){
        $sql="";
        if(is_array($fields)){
        $sets=array();
        foreach($fields as $key=>$vals){
            //判断是字符串则加上双引号
            if(is_string($vals)){
                $sets[$key]="{$key}='{$vals}'";
            }else{
                $sets[$key]="{$key}={$vals}";
            }
        }
        $value=  implode(",", $sets);
        if(!$value){
            return FALSE;
        }
        $sql="update {$this->tables} set {$value} ".($where?"where {$where}":"");
        }else
        {
            if(!$fields){
                return FALSE;
            }
            $sql="update {$this->tables} set {$fields} ".($where?"where {$where}":"");
        }
        $res=  $this->query($sql);
        if($res){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    //sql insert 插入方法,参数1：可以为数组，也可以为字符串，当是数组的时候格式如下：array("字段名"=>"值","字段名2"=>"值2"....)，当是字符串时候，格式如下：字段名=值,字段名2=值,...
    //参数2：当为true返回新插入的记录的id,否则不返回id
    public function insert($fields,$return_id=FALSE){
        $sql="";
        if(is_array($fields)){
        $key=  array_keys($fields);
        $keys=  implode(",", $key);
        foreach($fields as $key=>$vals){
            //判断是字符串则加上双引号
            if(is_string($vals)){
                $fields[$key]="'{$vals}'";
            }
        }
        $value=  implode(",", $fields);
        $sql="insert into {$this->tables} ({$keys}) values({$value})";
        }else
        {
            $tmp=  explode(",", $fields);
            $keys=array();
            $values=array();
            foreach ($tmp as $v){
                if(!empty($v)){
                $tmp2=  explode("=", $v);
                $keys[]=$tmp2[0];
                $values[]=$tmp2[1];
                }
            }
            $keys=  implode(",", $keys);
            $values= implode(",", $values);
            $sql="insert into {$this->tables} ({$keys}) values({$values})";
        }
        $res=  $this->query($sql);
        if($res){
            //执行成功!
            if($return_id){
               return $this->get_id();
            }else{
                return TRUE;
            }
            
        }else{
            return FALSE;
        }
    }
    //获得新插入一条的id
    public function get_id($sql="SELECT LAST_INSERT_ID() as id"){
        $res=$this->query($sql);
        $row =  ($this->ismysqli? mysqli_fetch_assoc($res):  mysql_fetch_assoc($res));
        $this->free_result($res);
        if(isset($row["id"])){
            return $row["id"];
        }else{
            return FALSE;
        }
    }
    //释放结果集
    public function free_result($res){
         $this->ismysqli? mysqli_free_result($res): mysql_free_result($res);
    }

    //mysql fetch_assoc方法
    public function get_fetch_assoc_method(){
       return($this->ismysqli? "mysqli_fetch_assoc":"mysql_fetch_assoc");
    }
     //mysql fetch_field_方法
    public function get_fetch_field_method(){
        return($this->ismysqli? "mysqli_fetch_field":"mysql_fetch_field");
    }
   //mysql fetch_row_方法
    public function get_fetch_row_method(){
        return($this->ismysqli? "mysqli_fetch_row":"mysql_fetch_row");
    }
    //mysql fetch_array_方法
    public function get_fetch_array_method(){
        return($this->ismysqli? "mysqli_fetch_array":"mysql_fetch_array");
    }
    //获得连接资源
    public function get_con(){
        return $this->con;
    }
    //载入数据库表对象，参数1：表名
    static public function load($table_name){
        if (is_null(self::$_instance)) {
            self::$_instance = new MysqlDB($table_name);
        }
        if($table_name){
            self::$_instance->set_table_name($table_name);
        }
        return self::$_instance;
    }
    //设置操作的表名
    public function set_table_name($table_name){
         global $_G;
         $this->tables=$_G["db"]["table_fix"]."_".$table_name;
    }
    //获得操作的表名
    public function get_table_name(){
        return $this->tables;
    }
}
